package org.uned.agonzalo16.bitacora.dao;

import static org.uned.agonzalo16.bitacora.dao.OfyFactory.ofy;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.uned.agonzalo16.bitacora.domain.Article;
import org.uned.agonzalo16.bitacora.domain.Blog;
import org.uned.agonzalo16.bitacora.domain.BlogContribution;

import com.googlecode.objectify.Key;

@Repository
public class BlogDao {

	@Autowired
	private ArticleDao articleDao;

	@Autowired
	private BlogContributionDao blogContributionDao;

	public List<Blog> findAll() {
		return ofy().load().type(Blog.class).list();
	}

	public Blog get(Long id) {
		return ofy().load().type(Blog.class).id(id).now();
	}

	public Blog merge(Blog blog) {
		ofy().save().entity(blog).now();
		return blog;
	}

	public void delete(Long id) {
		Blog blog = get(id);
		List<Key<Article>> articles = ofy().load().type(Article.class).filter("blog", blog).keys().list();
		for (Key<Article> article : articles) {
			articleDao.delete(article.getId());
		}
		List<BlogContribution> contributions = blogContributionDao.findByBlog(blog);
		for (BlogContribution contribution : contributions) {
			blogContributionDao.delete(contribution.getId());
		}
		ofy().delete().type(Blog.class).id(id).now();
	}
}
